package com.principles.structure.composite;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 组合模式：可以使用它将对象组合成树状结构，并且能够像使用独立对象一样使用它们
 * @Date 2025/1/30 22:06
 **/
public class CompositePattern {
    public static void main(String[] args) {
        Composite china = new Composite();
        Composite shandong  = new Composite();
        shandong.add(new City(100));
        shandong.add(new City(100));

        Composite shanxi = new Composite();
        shanxi.add(new City(100));
        shanxi.add(new City(100));
        china.add(shandong);
        china.add(shanxi);
        System.out.println(china.count());

    }
}

// 统计接口
interface Counter{
    int count();
}
// 叶子节点
class City implements Counter{

    private int sum = 0;

    public City(int sum) {
        this.sum = sum;
    }

    @Override
    public int count() {
        return sum;
    }
}

// 容器
class Composite implements Counter{

    private List<Counter> counterList = new ArrayList<>();

    public void add(Counter counter){
        counterList.add(counter);
    }

    public void delete(Counter counter){
        counterList.remove(counter);
    }
    public List<Counter> getChild(){
        return counterList;
    }
    @Override
    public int count() {
        int sum = 0;
        for(Counter counter:counterList){
            sum+=counter.count();
        }
        return sum;
    }
}